﻿using Custom.Framework;
using Custom.Model.Entity;
using Custom.Service.Repository;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace BackupTool
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ApplicationExit += Application_ApplicationExit;
            backup();
            //Application.Run(new Form1());
        }

        private static void Application_ApplicationExit(object sender, EventArgs e)
        {
            //Process.Start(AppDomain.CurrentDomain.BaseDirectory + @"BackupTool.exe");
        }

        static void backup()
        {
            try
            {
                string source = AppDomain.CurrentDomain.BaseDirectory + @"Custom.dll";

                bool f = File.Exists(source);
                string destPath = AppDomain.CurrentDomain.BaseDirectory.Substring(0, 1) + ":\\会员系统备份\\";
                string dest = string.Empty;

                SysConfig config = new SysConfigRepository().Get(w => w.code == "BackupConfig")?.FirstOrDefault();
                if (config == null)
                {
                    if (!Directory.Exists(destPath))
                    {
                        Directory.CreateDirectory(destPath);
                    }
                    dest = destPath + "Custom.dll(" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ")";
                }
                else
                {
                    dest = config.value + "\\Custom.dll(" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ")";
                }

                Logger.Error("sss == " + config.value + ", dest == " + dest);

                // 删除旧文件，保留最近10次备份
                DirectoryInfo dir = new DirectoryInfo(config.value);
                List<FileInfo> files = dir.GetFiles().OrderByDescending(o => o.LastWriteTime).Skip(9).ToList();
                foreach (var file in files)
                {
                    file.Delete();
                }

                File.Copy(source, dest);
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }
    }
}
